var express = require("express");
var router = express.Router();

const { hotModel, appreciateModel, newListModel,hotMoreModel } = require("../module/module");

/* GET home page. */
router.get("/", function (req, res, next) {
  res.render("index", { title: "Express" });
});
// 获取热销列表
router.get("/getHotList", async (req, res) => {
  try {
    const data = await hotModel.find();
    res.send(data);
  } catch (err) {
    console.log(err);
  }
});
// 获取更多热销列表
router.get("/getHotMoreList", async (req, res) => {
    try {
      const data = await hotMoreModel.find();
      res.send(data);
    } catch (err) {
      console.log(err);
    }
  });
// 获取热销列表单个商品
router.get("/getHostListByOne/:id", async (req, res) => {
  try {
    const productId = req.params.id;
    const product = await hotModel.findById(productId);
    if (!product) {
      return res.status(404).send({ msg: "商品不存在" });
    }
    res.send(product);
  } catch (err) {
    console.log(err);
  }
});
// 获取更多热销列表单个商品
router.get("/getHostMoreListByOne/:id", async (req, res) => {
    try {
      const productId = req.params.id;
      const product = await hotMoreModel.findById(productId);
      if (!product) {
        return res.status(404).send({ msg: "商品不存在" });
      }
      res.send(product);
    } catch (err) {
      console.log(err);
    }
  });
// 获取一番赏列表
router.get("/getAppreciateList", async (req, res) => {
  try {
    const data = await appreciateModel.find();
    res.send(data);
  } catch (err) {
    console.log(err);
  }
});
// 获取新品专区列表
router.get("/getNewList", async (req, res) => {
  try {
    const data = await newListModel.find();
    res.send(data);
  } catch (err) {
    console.log(err);
  }
});

const alipaySdk = require("../alipay");
// const AliPayForm = require("alipay-sdk/lib/form").default;
/// 支付宝支付
router.post("/alipay", async (req, res) => {
  try {
    let { orderId, totalPrice, name } = req.body;
    // const formData = new AliPayForm();

    // formData.setMethod("get");
    // formData.addField("returnUrl", "http://localhost:5173/home");
    // formData.addField("bizContent", {
    //   outTradeNo: orderId,
    //   productCode: "FAST_INSTANT_TRADE_PAY",
    //   totalAmount: totalPrice,
    //   subject: name,
    //   body: "商品详情",
    // });
    const bizContent = {
      outTradeNo: orderId,
      productCode: "FAST_INSTANT_TRADE_PAY",
      totalAmount: totalPrice,
      subject: name,
      body: "商品详情",
    };
    console.log("支付宝请求参数：", bizContent);
    const result = await alipaySdk.pageExec("alipay.trade.page.pay", {
      method: "GET",
      returnUrl: "http://localhost:5173/home",
      bizContent: bizContent,
    });

    res.send({
      data: {
        code: 200,
        success: true,
        msg: "支付链接生成成功",
        paymentUrl: result,
      },
    });
  } catch (error) {
    console.error("支付宝支付链接生成出错:", error);
    res.status(500).send({
      data: {
        code: 500,
        success: false,
        msg: "支付链接生成失败",
        error: error.message,
      },
    });
  }
});

// router.post("/alipay", async (req, res) => {
//   const { orderId, totalPrice, name } = req.body;
//   console.log(orderId, totalPrice, name);

//   // 创建 AlipayFormData 实例
//   const formData = new AlipaySdk();
//   // 设置请求方法为 get
//   formData.setMethod("get");

//   // 设置支付信息
//   const bizContent = {
//     out_trade_no: orderId,
//     product_code: "FAST_INSTANT_TRADE_PAY",
//     total_amount: totalPrice,
//     subject: name,
//     body: "商品详情",
//   };
//   formData.addField("bizContent", bizContent);

//   // 支付成功或失败的返回链接（前端页面）
//   formData.addField("returnUrl", "http://localhost:5173/home");

//   try {
//     // 调用支付宝 SDK 执行请求
//     const result = await alipaySdk.exec(
//       // PC调用
//       "alipay.trade.page.pay",
//       // 移动调用
//       // "alipay.trade.wap.pay",
//       {},
//       { formData: formData }
//     );

//     // 发送响应
//     res.send({
//       data: {
//         code: 200,
//         success: true,
//         msg: "支付中",
//         paymentUrl: result,
//       },
//     });
//   } catch (error) {
//     console.error("支付宝请求出错:", error);
//     res.status(500).send({
//       data: {
//         code: 500,
//         success: false,
//         msg: "支付请求失败",
//       },
//     });
//   }
// });

// 支付交易查询
router.post("/paymentQuery", async (req, res) => {
  const { out_trade_no, trade_no } = req.body;

  const formData = new AlipayFormData();
  formData.setMethod("get");

  const bizContent = {
    out_trade_no,
    trade_no,
  };
  formData.addField("bizContent", bizContent);

  try {
    const result = await alipaySdk.exec(
      "alipay.trade.query",
      {},
      { formData: formData }
    );

    const response = await axios.get(result);
    const responseCode = response.data.alipay_trade_query_response;

    if (responseCode.code == "10000") {
      switch (responseCode.trade_status) {
        case "WAIT_BUYER_PAY":
          res.send({
            code: 10001,
            message: "支付宝有交易记录，没付款",
          });
          break;
        case "TRADE_FINISHED":
        case "TRADE_SUCCESS":
          res.send({
            code: 10002,
            message: "交易完成",
          });
          break;
        case "TRADE_CLOSED":
          res.send({
            code: 10003,
            message: "交易关闭",
          });
          break;
      }
    } else if (responseCode.code == "40004") {
      res.send({
        code: 40004,
        message: "交易不存在",
      });
    }
  } catch (error) {
    console.error("支付查询失败:", error);
    res.status(500).send({
      code: 50000,
      msg: "交易查询失败",
      data: error,
    });
  }
});
module.exports = router;
